//SPI slave library 
// (c) 2013, M. Raimann
#include "spi_slave.h"

volatile uint8_t rxBuffer[BUFFER_SIZE];
volatile uint8_t txBuffer[BUFFER_SIZE];


SIGNAL(PCINT0_vect){
	//spi master started transmission -> reset bufferAddr and put first byte into SPDR register
	bufferAddr = 0;
	SPDR = txBuffer[bufferAddr];
}


SIGNAL(SPI_STC_vect){
	//after each transmitted byte, increase address counter
	rxBuffer[bufferAddr] = SPDR;
	bufferAddr++;
	
	//char tmp = SPSR;
	SPDR = txBuffer[bufferAddr];	
}

//Init spi slave - the rest ist done in the ISR -> enable global interrupts
void spiSlaveInit(void)
{
	//Set MISO as out, rest as input
	SPI_DDR|= (1<<MISO_PIN);
	SPI_DDR&= ~((1<<MOSI_PIN)|(1<<SCK_PIN)|(1<<SS_PIN));
	//Enable SS pullup
	SPI_PORT|= (1<<SS_PIN); 	

	SPCR = (1<<SPE)|(1<<SPIE);

	PCMSK0 = 	(1<<PCINT2); //Enable pin change interrupt on !SS
	PCICR = 	(1<<PCIE0);  // Enable pin change interrupt0

	//sei();
} 


